<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="body">
      <div class="project">
        <el-form
          :model="basicForm"
          label-position="top"
          :rules="basicRules"
          ref="basicFormRef"
        >
          <!-- 产出数据信息 -->
          <div class="project-part">
            <div class="project-part-title">
              产出数据信息
            </div>

            <el-row>
              <!-- <el-col :span="6">
                <el-form-item label="年月">
                  <el-cascader
                    v-model="basicForm.date"
                    :options="options"
                    :disabled="!isEdit"
                  >
                  </el-cascader>
                </el-form-item>
              </el-col> -->

              <el-col :span="6">
                <el-form-item label="企业名称" prop="name">
                  <!-- <el-input
                    v-model="basicForm.name"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input> -->
                  <el-select
                    v-model="basicForm.name"
                    :disabled="isDetail"
                    placeholder="请选择"
                    filterable
                    allow-create
                    @change="handleSelectChange"
                  >
                    <el-option
                      v-for="item in enterpriseOptions"
                      :key="item.socialCode"
                      :label="item.name"
                      :value="item.name"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="统一社会信用代码"
                  prop="socialCode"
                >
                  <el-input
                    v-model="basicForm.socialCode"
                    placeholder="请输入"
                    :disabled="isDetail || isExisting"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="类型">
                  <el-select
                    v-model="basicForm.type"
                    :disabled="isDetail"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in economicTypeOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- <el-row>
              <el-col :span="6">
                <el-form-item label="累计营收(万元)">
                  <el-input
                    v-model="basicForm.revenue"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="累计产值(万元)">
                  <el-input
                    v-model="basicForm.industryValue"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="累计全口径税收(万元)">
                  <el-input
                    v-model="basicForm.tax"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="外贸进出口值(万元)">
                  <el-input
                    v-model="basicForm.foreignTrade"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row> -->

            <!-- <el-row>
              <el-col :span="6">
                <el-form-item label="服务贸易额(万元)">
                  <el-input
                    v-model="basicForm.serviceValue"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="固定资产投资(万元)">
                  <el-input
                    v-model="basicForm.fixedAssets"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="固投是否为工业投资">
                  <el-select
                    v-model="basicForm.industryFlag"
                    :disabled="isDetail"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in isFixedInvestmentOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="本月完成FDI(万美元)">
                  <el-input
                    v-model="basicForm.finishValue"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row> -->

            <!-- <el-row>
              <el-col>
                <el-form-item label="是否规上企业">
                  <el-select
                    v-model="basicForm.enterpriseFlag"
                    :disabled="isDetail"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in isScaleEnterpriseOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row> -->
          </div>
        </el-form>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import {
  economicTypeOptions,
  isScaleEnterpriseOptions,
  isFixedInvestmentOptions
} from '@/utils/project/data'
import {
  addEnterpriseEconomic,
  enterpriseInfoQuery,
  addEnterpriseInfo
} from '@/api/dataManagement'
import dayjs from 'dayjs'

export default {
  props: {
    pkid: String,
    title: String,
    data: Object,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    year: String,
    month: String
  },
  components: {
    Breadcrumb
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        name: '',
        socialCode: '',
        type: '',
        enterpriseId: ''
        // date: '',
        // year: '',
        // month: '',
        // revenue: '',
        // industryValue: '',
        // tax: '',
        // foreignTrade: '',
        // serviceValue: '',
        // fixedAssets: '',
        // industryFlag: '',
        // finishValue: '',
        // enterpriseFlag: '',
        // type: ''
      },
      basicRules: {
        name: [
          {
            required: true,
            message: '请输入企业名称',
            trigger: 'blur'
          }
        ],
        socialCode: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      props: { multiple: true },
      options: [],
      enterpriseOptions: [],
      addEnterpriseInfo: {
        name: '',
        socialCode: '',
        type: '',
        enterpriseId: ''
      },
      isExisting: false
    }
  },
  computed: {
    titles() {
      return [this.title]
    },
    economicTypeOptions() {
      return economicTypeOptions
    },
    isScaleEnterpriseOptions() {
      return isScaleEnterpriseOptions
    },
    isFixedInvestmentOptions() {
      return isFixedInvestmentOptions
    }
  },
  watch: {},
  mounted() {
    this.isEdit
      ? (this.isExisting = true)
      : (this.isExisting = false)
    this.initMonth()
    this.getEnterpriseOptions()
  },
  methods: {
    handleSelectChange(val) {
      const value = String(val).trim()
      this.isExisting = this.enterpriseOptions.some(
        (item) => item.name === value
      )
      if (!this.isExisting) {
        this.addEnterpriseInfo.name = value
        this.basicForm.socialCode = ''
      } else {
        const enterpriseInfo = this.enterpriseOptions.find(
          (item) => item.name === value
        )
        this.basicForm.socialCode =
          enterpriseInfo.socialCode
        this.basicForm.name = enterpriseInfo.name
        this.basicForm.type = enterpriseInfo.type
        this.addEnterpriseInfo.enterpriseId =
          enterpriseInfo.pkid
      }
    },
    getEnterpriseOptions() {
      enterpriseInfoQuery({
        pageIndex: 1,
        pageSize: 999
      }).then((res) => {
        this.enterpriseOptions = res.data.list
      })
    },
    initMonth() {
      const date = new Date()

      if (!this.isEdit) {
        const month = dayjs(date)
          .subtract(1, 'month')
          .format('YYYY-M')
        this.basicForm.date = [
          month.split('-')[0],
          month.split('-')[1]
        ]
      }

      let monthList = []
      for (let i = 0; i < 12; i++) {
        monthList.push({
          label: (i + 1).toString(),
          value: (i + 1).toString()
        })
      }
      const year = date.getFullYear()
      this.options = [
        {
          value: year.toString(),
          label: year.toString(),
          children: monthList
        },
        {
          value: (year - 1).toString(),
          label: (year - 1).toString(),
          children: monthList
        }
      ]

      if (this.pkid) {
        this.basicForm = JSON.parse(
          JSON.stringify(this.data)
        )
        this.basicForm.date = [
          `${this.data.year}`,
          `${this.data.month}`
        ]
      }
    },
    // 保存信息
    async saveInfo() {
      this.$refs.basicFormRef.validate(async (res) => {
        if (res) {
          try {
            // 如果是新企业，先添加企业信息
            if (!this.isExisting) {
              this.addEnterpriseInfo.enterpriseId = ''
              this.addEnterpriseInfo.socialCode =
                this.basicForm.socialCode
              this.addEnterpriseInfo.type =
                this.basicForm.type
              this.addEnterpriseInfo.name =
                this.basicForm.name

              // const enterpriseRes = await addEnterpriseInfo(this.addEnterpriseInfo)
              // if (!enterpriseRes.success) {
              //   this.$message.error(enterpriseRes.message || '企业信息保存失败')
              //   return
              // }
              // this.$message.success('企业信息新增成功')
            }
            this.basicForm.year = this.year
            this.basicForm.month = this.month
            this.basicForm.enterpriseId =
              this.addEnterpriseInfo.enterpriseId
            // 添加经济数据
            const economicRes = await addEnterpriseEconomic(
              this.basicForm
            )
            if (economicRes.success) {
              this.$message.success(
                this.basicForm.pkid
                  ? '编辑成功'
                  : '新增成功'
              )
              this.$router.push({
                path: '/dataManagement/enterpriseManagement/enterpriseEconomic/list',
                query: { refresh: Date.now() }
              })
            } else {
              this.$message.error(economicRes.message)
            }
          } catch (error) {
            console.error('保存失败:', error)
            this.$message.error('保存失败，请重试')
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .body {
    padding: 10px 0 0 20px;

    // &-left {
    //   width: 70%;
    //   border-right: 1px solid #f1f1f1;
    //   overflow: scroll;
    // }

    // &-right {
    //   flex: 1;
    //   padding-left: 10px;
    // }

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .line {
    display: flex;
    justify-content: center;
  }
}
</style>
